using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

using FarseerGames.FarseerPhysics.Dynamics;
using FarseerGames.FarseerPhysics.Collisions;

using TRead = ProjectNoClue.Part;

namespace ProjectNoClue.Pipeline.Readers
{
	public class PartReader : ContentTypeReader<TRead>
	{
		protected override TRead Read(ContentReader input, TRead existingInstance)
		{
			if (existingInstance == null)
				existingInstance = new Part();

			existingInstance.Position = input.ReadVector2();
			existingInstance.Rotation = input.ReadSingle();
			existingInstance.Shapes = new Part.Shape[input.ReadInt32()];
			for (int ii = 0; ii < existingInstance.Shapes.Length; ++ii)
			{
				existingInstance.Shapes[ii] = new Part.Shape();
				ReadShape(input, existingInstance.Shapes[ii]);
			}

			existingInstance.Body = new Body();
			existingInstance.Body.Position = existingInstance.position;
			existingInstance.Body.Rotation = existingInstance.rotation;
			existingInstance.Body.Mass = 1;


			//TODO: Move this to the processor
			Part.Shape[] shapes = existingInstance.Shapes;
			Vertices vert;
			float moi = 0;
			for (int ii = 0; ii < shapes.Length; ++ii)
			{
				vert = new Vertices(shapes[ii].Vertices);
				vert.SubDivideEdges(5);
				moi += vert.GetMomentOfInertia();

				shapes[ii].Geom = GeomFactory.Instance.CreatePolygonGeom(existingInstance.Body, vert, 0);
				shapes[ii].Geom.FrictionCoefficient = .5f;
				shapes[ii].Geom.RestitutionCoefficient = 0;
			}
			existingInstance.Body.MomentOfInertia = moi;
	
			return existingInstance;
		}

		void ReadShape(ContentReader input, Part.Shape existingInstance)
		{

			existingInstance.ShapeColor = new Color();
			existingInstance.ShapeColor.PackedValue = input.ReadUInt32();

			existingInstance.Vertices = new Vector2[input.ReadInt32()];
			for (int ii = 0; ii < existingInstance.Vertices.Length; ++ii)
			{
				existingInstance.Vertices[ii] = input.ReadVector2();
			}

			existingInstance.HiddenEdges = new int[input.ReadInt32()];
			for (int ii = 0; ii < existingInstance.HiddenEdges.Length; ++ii)
			{
				existingInstance.HiddenEdges[ii] = input.ReadInt32();
			}

			existingInstance.Edges = new Part.Shape.Edge[input.ReadInt32()];
			for (int ii = 0; ii < existingInstance.Edges.Length; ++ii)
			{
				ReadEdge(input, out existingInstance.Edges[ii]);
			}
		}

		void ReadEdge(ContentReader input, out Part.Shape.Edge existingInstance)
		{
			existingInstance.LenghtSinCos = input.ReadVector3();
			existingInstance.Point = input.ReadVector2();
		}
	}
}
